//
//  UUProductStateListVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 04/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUProductStateListVC.h"
#import "UUProductManager.h"
#import "UUPermissionManager.h"
#import "UUFleetManager.h"
#import "UUBaseTableViewCell.h"
#import <UUFoundation/NSAttributedString+Extensions.h>
#import "UUProductEditVC.h"

@interface UUProductCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *priceLabel;

@end

@implementation UUProductCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.titleLabel = [UILabel new];
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        self.titleLabel.textColor = COMMON_TEXT_BLACK_COLOR;
        [self.contentView addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.left.mas_equalTo(14);
            make.right.mas_equalTo(-14);
            make.height.mas_equalTo(21);
        }];
        
        self.priceLabel = [UILabel new];
        self.priceLabel.textColor = COMMON_TEXT_RED_COLOR;
        [self.contentView addSubview:self.priceLabel];
        [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.right.mas_equalTo(-10);
            make.height.mas_equalTo(27);
        }];
    }
    return self;
}

- (void)setupWithProductModel:(UUProductModel *)product {
    UUFleetModel *fleet = [GetFleetManager() fetchFleetWithFleetId:product.fleetId];
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:fleet.name ?: @""
                                                                                       attributes:@{
                                                                                                    NSForegroundColorAttributeName : self.titleLabel.textColor,
                                                                                                    NSFontAttributeName : self.titleLabel.font
                                                                                                    }];
    UIImage *image = nil;
    if (product.onlineStatus == UUProductOnlineStatusOffline && product.status == UUProductReviewStatusApproval) { // 下架，已审核
        image = [UIImage imageNamed:@"ProductReviewStatusApproved"];
    } else if (product.onlineStatus == UUProductOnlineStatusOffline && product.status == UUProductReviewStatusWaitingForReview) { // 下架，待审核
        image = [UIImage imageNamed:@"ProductReviewStatusWaitingForReview"];
    }
    
    if (image != nil) {
        [attributedText addImage:image offset:CGPointMake(10, 2)];
    }
    
    self.titleLabel.attributedText = attributedText;
    
    NSMutableAttributedString *priceAttributedText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@起", [product.minPrice toCurrency]]
                                                                                       attributes:@{
                                                                                                    NSForegroundColorAttributeName : self.priceLabel.textColor,
                                                                                                    NSFontAttributeName : [UIFont systemFontOfSize:19]
                                                                                                    }];
    [priceAttributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, 1)];
    [priceAttributedText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(priceAttributedText.length - 1, 1)];
    self.priceLabel.attributedText = priceAttributedText;
}

@end

//////////////////////////////////////////////////////////////////////////////

@interface UUProductStateListVC () <UUProductManagerObserver>

@property (nonatomic, copy) NSArray<NSNumber *> *reviewStatus;
@property (nonatomic, copy) NSArray<NSNumber *> *onlineStatus;
@property (nonatomic, strong) NSNumber *carCategoryId;

@property (nonatomic, copy) NSArray<id> *products;

@end

@implementation UUProductStateListVC

+ (instancetype)listWithReviewStatus:(NSArray<NSNumber *> *)reviewStatus onlineStatus:(NSArray<NSNumber *> *)onlineStatus carCategoryId:(NSNumber *)carCategoryId {
    UUProductStateListVC *listVC = [self instanceOfAppropriate];
    listVC.reviewStatus = reviewStatus;
    listVC.onlineStatus = onlineStatus;
    listVC.carCategoryId = carCategoryId;
    
    return listVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerClass:[UUProductCell class] forCellReuseIdentifier:@"Cell"];
    self.tableView.rowHeight = 58;
    
    [self reload];
    
    [GetProductManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)reload {
    self.products = [GetProductManager() fetchProductsWithReviewStatus:self.reviewStatus onlineStatus:self.onlineStatus carCategoryId:self.carCategoryId];
    [self.tableView reloadData];
}

- (void)updateCarCategoryId:(NSNumber *)carCategoryId {
    self.carCategoryId = carCategoryId;
    
    [self reload];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSNumber *productId = self.products[indexPath.row];
    UUProductModel *productModel = [GetProductManager() fetchProductModelWithProductId:productId];
    [cell setupWithProductModel:productModel];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSNumber *productId = self.products[indexPath.row];
    
    UUProductEditVC *productEditVC = [UUProductEditVC instanceOfAppropriate];
    productEditVC.productId = productId;
    [self.navigationController pushViewController:productEditVC animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if ([GetPermissionManager() checkPermission:UUPermissionFlagProductReadWrite]) {
        NSNumber *productId = self.products[indexPath.row];
        UUProductModel *productModel = [GetProductManager() fetchProductModelWithProductId:productId];
        
        return productModel.onlineStatus == UUProductOnlineStatusOffline;
    } else {
        return NO;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [UIAlertController presentAlertControllerWithTitle:@"确定删除该产品吗？" message:nil doneBlock:^{
            NSNumber *productId = self.products[indexPath.row];
            
            ShowIndicator();
            WEAK_SELF();
            [GetProductManager() asyncDeleteProductWithProductId:productId completeBlock:^(NSError *error) {
                HideIndicatorInView(weakSelf.view);
                
                if (error != nil) {
                    ShowTipsOnView(error.localizedDescription, weakSelf.view);
                }
            }];
        } cancelBlock:nil];
    }
}

#pragma mark - UUProductManagerObserver methods

- (void)productManagerDidUpdateProducts:(NSArray<NSNumber *> *)products {
    [self reload];
}

- (void)productManagerDidRemoveProducts:(NSArray<NSNumber *> *)products {
    if (self.products.count > 0) {
        NSMutableArray<NSIndexPath *> *indexPathes = [NSMutableArray array];
        NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
        for (int j = 0; j < products.count; ++j) {
            for (int i = 0; i < self.products.count; ++i) {
                if ([self.products[i] isEqual:products[j]]) {
                    [indexPathes addObject:[NSIndexPath indexPathForRow:i inSection:0]];
                    [indexSet addIndex:i];
                    break;
                }
            }
        }
        
        NSMutableArray<NSNumber *> *mutableProducts = [self.products mutableCopy];
        [mutableProducts removeObjectsAtIndexes:indexSet];
        self.products = mutableProducts;
        [self.tableView deleteRowsAtIndexPaths:indexPathes
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

@end
